定义
定义一个操作中算法的骨架,将一些步骤延迟到子类中。模板方法使得子类可以不改变算法的结果即可重定义该算法的某些特定步骤。
简单理解成
同样一套代码,要有不同输出。
UML
示例代码
abstract class Template {
public abstract void OperationA();
public abstract void OperationB();
//定义模板调用顺序
public void TemplateMethod() {
OperationA();
OperationB();
}
}
public class SubClassA extends Template {
@Override
public void OperationA() {
// TODO Auto-generated method stub
System.out.println("A want a car");
}
@Override
public void OperationB() {
// TODO Auto-generated method stub
System.out.println("A don't need a girfriend");
}
}
public class SubClassB extends Template {
@Override
public void OperationA() {
// TODO Auto-generated method stub
System.out.println("B don't need a car");
}
@Override
public void OperationB() {
// TODO Auto-generated method stub
System.out.println("B need a girlfriend");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Template t;
t = new SubClassA();
t.TemplateMethod();
t = new SubClassB();
t.TemplateMethod();
}
//输出 A和B用一套模板,不同输出
A want a car
A don't need a girfriend
B don't need a car
B need a girlfriend
通过把不变行为搬到超类,去除子类的重复代码体现优势。